
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { login, getUserProfile } from '@/api/auth';
import { useUserStore } from '@/stores/modules/user';

/**
 * 登录页面组合式函数
 * 提供登录相关的响应式数据和方法
 */
export function useLogin() {
  const router = useRouter();
  const loading = ref(false);
  const userStore = useUserStore();

  // 登录表单数据
  const loginForm = reactive({
    username: 'admin',
    password: 'admin123',
  });

  // 表单验证规则
  const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  };

  /**
   * 处理登录操作
   * @param {Object} values - 表单数据
   */
  const handleLogin = async (values) => {
    loading.value = true;
    try {
      // 调用登录API
      const loginResponse = await login({
        username: values.username,
        password: values.password,
      });

      if (loginResponse.accessToken) {
        // 保存token到localStorage
        localStorage.setItem('token', loginResponse.accessToken);

        // 获取用户信息
        const userInfo = await getUserProfile();

        // 保存用户信息到store
        userStore.setUserInfo(userInfo);

        // 绑定用户信息到监控系统
        if (window.$webTracing) {
          window.$webTracing.setUser({
            userId: userInfo.id,
            userName: userInfo.name || userInfo.username,
            userEmail: userInfo.email,
          });
          console.log('[监控] 用户信息已绑定:', userInfo.username);
        }

        // 构造动态路由
        userStore.generateRoutes(userInfo.menus);

        message.success('登录成功');
        router.push('/dashboard');
      } else {
        message.error('登录失败：未获取到token');
      }
    } catch (error) {
      message.error('登录失败：' + (error.message || '未知错误'));
    } finally {
      loading.value = false;
    }
  };

  /**
   * 跳转到注册页面
   */
  const goToRegister = () => {
    router.push('/register');
  };

  return {
    loginForm,
    rules,
    loading,
    handleLogin,
    goToRegister,
  };
}

